import { ipcMain, shell } from 'electron'
import { WindowController } from '../window'
import { TaskExecutor, ExampleTask } from '../playwright'
import { rendererLogger } from '../logger'
import mainLogger from '../logger'
import { AppInfo } from '../config/app-info'
import ConfigManager from '../config/configManager'
import { checkVIP } from '../custom/checkVIP'

/**
 * 注册所有 IPC 处理器
 */
export function registerIPCHandlers(): void {
  const configManager = new ConfigManager()

  // 获取应用信息
  ipcMain.handle('get-app-info', () => {
    return AppInfo.getAppInfo()
  })

  // 登录验证
  ipcMain.handle('login', async (_, loginId: string, loginKey: string) => {
    try {
      const result = await checkVIP({ vipUserId: loginId, vipUserKey: loginKey })
      if (result.code === 0 && result.result) {
        // 登录成功，保存配置
        configManager.setConfig('login', {
          loginId,
          loginKey
        })
        return { success: true, message: result.msg }
      } else {
        return { success: false, message: result.msg || '登录失败' }
      }
    } catch (error) {
      const message = error instanceof Error ? error.message : '未知错误'
      return { success: false, message: `登录异常: ${message}` }
    }
  })

  // 保存应用配置
  ipcMain.handle('save-app-config', (_, key: string, value: unknown) => {
    try {
      if (key === 'login' || key === 'settings') {
        configManager.setConfig(key as 'login' | 'settings', value as never)
      }
      return { success: true }
    } catch (error) {
      const message = error instanceof Error ? error.message : '未知错误'
      return { success: false, message }
    }
  })

  // 获取应用配置
  ipcMain.handle('get-app-config', (_, key: string) => {
    try {
      if (key === 'login' || key === 'settings') {
        return configManager.getConfig(key as 'login' | 'settings')
      }
      return null
    } catch {
      return null
    }
  })

  // 打开外部链接
  ipcMain.handle('open-external', async (_, url: string) => {
    try {
      await shell.openExternal(url)
      return { success: true }
    } catch (error) {
      const message = error instanceof Error ? error.message : '未知错误'
      return { success: false, message }
    }
  })

  // 窗口控制 IPC 处理
  ipcMain.on('window-minimize', () => {
    WindowController.minimize()
  })

  ipcMain.on('window-maximize', () => {
    WindowController.toggleMaximize()
  })

  ipcMain.on('window-fullscreen', (_, fullscreen: boolean) => {
    WindowController.setFullScreen(fullscreen)
  })

  // Playwright 调用处理
  ipcMain.on('startPlaywright', async () => {
    try {
      mainLogger.info('开始执行 Playwright 任务')
      const executor = new TaskExecutor()
      executor.addTask(new ExampleTask())
      await executor.execute(false) // 非 headless 模式，可以看到浏览器
      mainLogger.info('Playwright 任务执行完成')
    } catch (error) {
      mainLogger.error('Playwright 任务执行失败', { error })
    }
  })

  // 打开开发者工具
  ipcMain.on('open-devtools', () => {
    const mainWindow = WindowController.getMainWindow()
    if (mainWindow) {
      mainWindow.webContents.openDevTools()
    }
  })

  // 日志IPC处理 - 允许渲染进程发送日志到主进程
  ipcMain.on(
    'log',
    (_, logData: { level: string; message: string; meta?: Record<string, unknown> }) => {
      const { level, message, meta } = logData
      switch (level) {
        case 'debug':
          rendererLogger.debug(message, meta)
          break
        case 'info':
          rendererLogger.info(message, meta)
          break
        case 'warn':
          rendererLogger.warn(message, meta)
          break
        case 'error':
          rendererLogger.error(message, meta)
          break
        default:
          rendererLogger.info(message, meta)
      }
    }
  )
}
